<template>
  <div class="app-container">
        <el-form
          ref="dataForm"
          :rules="rules" 
          :model="sizeForm" 
          label-position="left" 
          label-width="100px" 
          style="width:800px;"
          >

          <el-form-item label="名称" prop="name">
            <el-input v-model="sizeForm.name" />
          </el-form-item>

          <!-- <el-form-item label="时间段" prop="start_time">
            <el-time-picker
              is-range
              arrow-control
              v-model="sizeForm.valid_time"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
              value-format="HH:mm"
              >
            </el-time-picker>
          </el-form-item> -->
          <el-form-item label="开始时间" prop="start_time">
            <!-- <el-input v-model="sizeForm.limit_num" type="number" /> -->
            <el-time-picker
              arrow-control
              v-model="sizeForm.start_time"
              placeholder="请选择开始时间"
              value-format="HH:mm"
              >
            </el-time-picker>

          </el-form-item>

          <el-form-item label="结束时间" prop="end_time">
            <el-time-picker
              arrow-control
              v-model="sizeForm.end_time"
              placeholder="请选择结束时间"
              value-format="HH:mm"
              >
            </el-time-picker>
          </el-form-item>

          <el-form-item label="参与人数" prop="limit_num">
            <el-input v-model="sizeForm.limit_num" type="number" />
          </el-form-item>

          <el-form-item label="设置标签" prop="limit_num">
            <el-select
              v-model="sizeForm.tag"
              multiple
              placeholder="请选择">
              <el-option
                v-for="item in tagItem"
                :key="'tagItem' + item.tag_id"
                :label="item.name"
                :value="item.tag_id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="封面图" prop="banner">
            <imageUpload
              ref="banner" 
              :limit="3"
              :list="sizeForm.banner"
            ></imageUpload>
          </el-form-item>

          <el-form-item label="训练效果">
            <el-input type="textarea" v-model="sizeForm.training_result" :autosize="{ minRows: 6, maxRows: 6}"></el-input>
          </el-form-item>

          <el-form-item label="注意事项">
            <el-input type="textarea" v-model="sizeForm.precautions" :autosize="{ minRows: 6, maxRows: 6}"></el-input>
          </el-form-item>

          <el-form-item label="适应人群">
            <el-input type="textarea" v-model="sizeForm.suitable" :autosize="{ minRows: 6, maxRows: 6}"></el-input>
          </el-form-item>

          <el-form-item label="约课步骤" prop="appointment_img">
            <imageUpload
              ref="appointment_img" 
              :limit="1"
              :list="sizeForm.appointment_img"
            ></imageUpload>
          </el-form-item>

          <el-form-item label="课程简介" prop="introduction">
            <tinymce v-model="sizeForm.introduction" ref="tinymce"></tinymce>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="createdData()">
                确定
            </el-button>
          </el-form-item>
        </el-form>
  </div>
</template>

<script>
import imageUpload from "@/components/imageUpload"
import tinymce from "@/components/Tinymce"

export default {
  name: 'addProject',
  components: {
    imageUpload,
    tinymce
  },
  data() {
    return {
      sizeForm: {
        name: "",
        start_time: "",
        end_time: "",
        limit_num: "",
        introduction: "",
        precautions: "",
        suitable: "",
        banner: [],
        training_result: "",
        appointment_img: [],
        tag: [],
        start_time:"",
        end_time:"",
        valid_time: ['8:00', '9:00']     //时间段（开始 + 结束时间）
      },
      //test: [new Date(2019, 9, 10, 8, 40), new Date(2019, 9, 10, 9, 40)],

      //校验规则
      rules: {
        name: [{ required: true, message: '请输入名称' }],
        banner: [{ required: true, message: '请上传背景图' }],
        //valid_time: [{ required: true, message: '请选择时间段' }],
        start_time: [{ required: true, message: '请选择开始时间' }],
        end_time: [{ required: true, message: '请选择结束时间' }],
      },

      projectItem: [],    //课程数据
      tagItem: [],        //标签数据
      nowId: '',
    }
  },
  created() {
    const vm = this;
  },
  computed: {

  },
  methods: {
    async getprojectItem(id) {
      id = id || ''
      const vm = this;
      let url = api.project + (id ? '/' + id : '')
      vm.$axios.get(url)
        .then((res) => {
          vm.resetForm()
          vm.sizeForm.name = res.name
          vm.sizeForm.start_time = res.start_time
          vm.sizeForm.end_time = res.end_time
          //vm.sizeForm.valid_time = [res.start_time, res.end_time]
          vm.sizeForm.start_time = res.start_time
          vm.sizeForm.end_time = res.end_time
          vm.sizeForm.limit_num = res.limit_num
          vm.sizeForm.introduction = res.introduction
          vm.sizeForm.precautions = res.precautions
          vm.sizeForm.suitable = res.suitable
          vm.sizeForm.training_result = res.training_result
          //vm.sizeForm.appointment_img = res.appointment_img
          //vm.sizeForm.tag = res.tag

          //tag处理
          for (let i = 0; i < res.tag.length; i++) {
            vm.sizeForm.tag.push(res.tag[i].tag_id)
          }

          //约课步骤处理
          vm.sizeForm.appointment_img.push(res.appointment_img)

          //背景图处理
          for (let i = 0; i < res.banner.length; i++) {
            vm.sizeForm.banner.push(res.banner[i].url)
          }

          //重置富文本
          vm.$refs['tinymce'].setContent(res.introduction)
        })
    },

    async getTagItem(id) {
      id = id || ''
      const vm = this;
      let url = api.tag + (id ? '/' + id : '')
      vm.$axios.get(url)
        .then((res) => {
          //console.log(res)
          vm.$set(vm, 'tagItem', res.data)
        })
    },

    createdData() {
      const vm = this;
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const _data = JSON.parse(JSON.stringify(vm.sizeForm))
          //数据过滤

          let postData = {
            name: _data.name,
            start_time: _data.start_time,
            end_time: _data.end_time,
            limit_num: _data.limit_num,
            introduction: _data.introduction,
            precautions: _data.precautions,
            suitable: _data.suitable,
            training_result: _data.training_result,
            appointment_img: _data.appointment_img[0],
            tag: _data.tag,
            banner: _data.banner
          }

          if (!postData.banner.length) {
            vm.$message({
              message: '请至少上传一张背景图',
              type: 'error'
            })
            return false
          }
          //console.log(postData)
          //return false
          //判断是否编辑
          const id = vm.nowId
          let url = api.project
          let method = 'post'
          if (id) {
            url = url + '/' + id
            method = 'put'
          } else {
            //获取图片
            postData.banner = vm.$refs['banner'].list
            postData.appointment_img = vm.$refs['appointment_img'].list[0]
          }

          //console.log(postData)
          //return false
          vm.$axios[method](url, postData)
            .then((res) => {
              vm.$message({
                message: "成功",
                type: 'success'
              })
              vm.resetForm()
              setTimeout(() => {
                //vm.resetForm()
                vm.$router.push({
                  path: "/project/projectList"
                })
              }, 1500);
            })
        }
      })
    },

    resetForm() {
      const vm = this;
      vm.sizeForm = {
        name: "",
        start_time: "",
        end_time: "",
        limit_num: "",
        introduction: "",
        precautions: "",
        suitable: "",
        banner: [],
        training_result: "",
        appointment_img: [],
        tag: [],
        //valid_time: ['8:00', '9:00']     //时间段（开始 + 结束时间）
        start_time:"",
        end_time:""
      }


      if (window.tinymce) {     //防止第一次进来的时候富文本还未初始化引发BUG
        vm.$refs['tinymce'].setContent('')
      }
    }

  }, //method

  //页面显示的时候触发
  async activated() {
    const vm = this
    //第一次创建的时候判断有没有参数
    if (vm.$route.query.id) {
      let id = vm.$route.query.id
      vm.nowId = id

      await vm.getTagItem()
      vm.getprojectItem(id)
    } else {
      vm.resetForm()
      vm.getTagItem()
    }
  }
}
</script>

<style scoped>
</style>
